<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { jwtDecode } from 'jwt-decode';

const route = useRoute();
const router = useRouter();
const doctors = ref([]);
const loading = ref(false);
const username = ref<string | null>(null);
const avatar = ref<string | null>(null);
const searchQuery = ref(route.query.q || ''); // 设置初始值为路由参数中的 `q`

const navigationItems = [
    { name: '问医生', link: '/sections' },
    { name: '查疾病', link: '/disease' },
    { name: '查药品', link: '/medicine' },
    { name: '查医院', link: '/hospital' },
    { name: '查检查/手术', link: '/examination' },
    { name: '查疫苗', link: '/vaccine' },
    { name: '急救指南', link: '/emergency' },
    { name: '测一测', link: '/test' },
    { name: '科普视频', link: '/videos' }
];

const fetchUserInfo = async () => {
    const token = localStorage.getItem('token');
    if (token) {
        const payload = ref<any>(jwtDecode(token));
        username.value = payload.value.username;
        avatar.value = 'http://127.0.0.1:8000/uploads/' + payload.value.avatar;
    }
};

const logout = () => {
    localStorage.removeItem('token');
    username.value = null;
    avatar.value = null;
};

const handleSearch = () => {
    if (searchQuery.value.trim()) {
        router.push({
            path: '/search',
            query: { q: searchQuery.value }
        });
    }
};

const fetchDoctors = async () => {
    loading.value = true;
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/search/?text=${route.query.q || ''}`);
        doctors.value = response.data;
    } catch (error) {
        console.error('搜索失败:', error);
    } finally {
        loading.value = false;
    }
};

const highlightText = (text: string) => {
    if (!route.query.q) return text;
    const regex = new RegExp(`(${route.query.q})`, 'gi');
    return text.replace(regex, '<span class="highlight">$1</span>');
};

// 监听路由变化，重新触发搜索操作
watch(() => route.query.q, (newQuery) => {
    searchQuery.value = newQuery || '';
    fetchDoctors();
});

onMounted(() => {
    fetchDoctors();
    fetchUserInfo();
});
</script>

<template>
    <div class="min-h-screen bg-gray-50">
        <!-- Header -->
        <header class="header">
            <div class="container">
                <div class="links-container">
                    <a href="#" class="flex items-center text-gray-600 hover:text-primary">
                        <i class="icon-download"></i>
                        <span class="ml-1">下载App</span>
                    </a>
                    <a href="#" class="text-primary font-bold hover:underline">栏目收费说明</a>
                </div>
                <div v-if="!username" class="auth-buttons">
                    <RouterLink class="btn-login" :to="{ name: 'Login', query: { redirecturl: route.fullPath } }">
                        登录
                    </RouterLink>
                    <RouterLink class="btn-register" to="/register">注册</RouterLink>
                </div>
                <div v-else class="user-info">
                    <img :src="avatar" alt="用户头像" class="user-avatar" />
                    <span class="username">{{ username }}</span>
                    <button class="text-logout" @click="logout">退出</button>
                </div>
            </div>
        </header>

        <!-- Search -->
        <div class="search-container">
            <h1 class="brand-title">丁香医生</h1>
            <form @submit.prevent="handleSearch" class="search-wrapper">
                <input v-model="searchQuery" type="text" placeholder="搜索疾病、医院、药品" class="search-input" />
                <button type="submit" class="search-button">
                    <i class="icon-search"></i>
                    搜索
                </button>
            </form>
        </div>

        <!-- Navigation -->
        <nav class="main-nav">
            <router-link v-for="item in navigationItems" :key="item.name" :to="item.link" class="nav-link">
                {{ item.name }}
            </router-link>
        </nav>

        <!-- Main Content -->
        <main class="main-content">
            <div class="search-results">
                <h2 class="section-title">搜索结果</h2>

                <div v-if="loading" class="loading-spinner">
                    <div class="spinner"></div>
                </div>

                <div v-else-if="doctors.length === 0" class="no-results">
                    <p>暂无相关搜索结果</p>
                </div>

                <div v-else class="doctors-list">
                    <div v-for="doctor in doctors" :key="doctor.id" class="doctor-card" @click="router.push(`/doctor/${doctor.id}`)">
                        <div class="doctor-info">
                            <img :src="doctor.avatar" :alt="doctor.name" class="doctor-avatar" />
                            <div class="doctor-details">
                                <div class="doctor-header">
                                    <div>
                                        <a :href="`/doctor/${doctor.id}`" class="doctor-name"
                                            v-html="highlightText(doctor.name)"></a>
                                        <p class="doctor-title">
                                            {{ doctor.get_title_display }} |
                                            <a :href="`/hospital/${doctor.hospital_id}`" class="hospital-link"
                                                v-html="highlightText(doctor.hospital)"></a>
                                        </p>
                                        <p class="department">{{ doctor.department }}</p>
                                    </div>
                                    <div class="price-info">
                                        <p class="price">¥{{ doctor.consultation_price }}</p>
                                        <p class="consultation-type">图文问诊</p>
                                    </div>
                                </div>
                                <div class="stats">
                                    <span>评分 <strong class="rating">{{ doctor.rating }}</strong></span>
                                    <span>问诊量 {{ doctor.consultation_count }}</span>
                                    <span>平均响应 {{ doctor.avg_response_time }}分钟</span>
                                </div>
                                <p class="introduction" v-html="highlightText(doctor.introduction)"></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- Footer -->
        <footer class="footer">
            <div class="bottom-links">
                <a target="_blank" href="http://www.dxy.cn/pages/copyright.html" rel="nofollow">版权声明</a>
                <a target="_blank" href="https://dxy.com/column/board" rel="nofollow">作者编委</a>
                <a target="_blank" href="https://ask.dxy.com/ama/index" rel="nofollow">丁香医生</a>
                <a href="mailto:doctor@dxy.com" rel="nofollow">投稿邮箱 doctor@dxy.com</a>
                <a>客服电话：0571-22931767</a>
            </div>
        </footer>
    </div>
</template>


<style scoped>
/* Header Styles */
.header {
    background-color: #ffffff;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.container {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 24px;
}

.links-container {
    display: flex;
    align-items: center;
    gap: 16px;
}

.links-container a {
    color: #666666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.3s ease;
}

.text-primary {
    color: #00b38a;
}

.auth-buttons {
    display: flex;
    gap: 16px;
}

.btn-login,
.btn-register {
    color: #666666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.3s ease;
}

.btn-login:hover,
.btn-register:hover {
    color: #00b38a;
    text-decoration: underline;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    object-fit: cover;
}

.username {
    font-size: 14px;
    color: #333333;
}

.text-logout {
    background: none;
    border: none;
    color: #666666;
    font-size: 14px;
    cursor: pointer;
    padding: 0;
}

.text-logout:hover {
    color: #00b38a;
    text-decoration: underline;
}

/* Search Styles */
.search-container {
    background-color: #fff;
    padding: 20px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 2rem;
    max-width: 1200px;
    margin: 0 auto;
}

.brand-title {
    font-size: 32px;
    font-weight: 700;
    color: #00b38a;
    margin: 0;
    letter-spacing: 1px;
    white-space: nowrap;
}

.search-wrapper {
    flex: 1;
    max-width: 600px;
    display: flex;
    gap: 10px;
}

.search-input {
    flex: 1;
    padding: 12px 20px;
    border: 2px solid #00b38a;
    border-radius: 24px;
    font-size: 16px;
    outline: none;
    transition: box-shadow 0.3s ease;
}

.search-input:focus {
    box-shadow: 0 0 0 3px rgba(0, 179, 138, 0.1);
}

.search-button {
    padding: 12px 30px;
    background-color: #00b38a;
    color: white;
    border: none;
    border-radius: 24px;
    cursor: pointer;
    font-size: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: background-color 0.3s ease;
}

.search-button:hover {
    background-color: #009e7a;
}

/* Navigation Styles */
.main-nav {
    background-color: #fff;
    padding: 12px 0;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: center;
    gap: 16px;
}

.nav-link {
    padding: 8px 16px;
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.2s;
    white-space: nowrap;
}

.nav-link:hover {
    color: #00b38a;
}

.nav-link.router-link-active {
    color: #00b38a;
    font-weight: 500;
}

/* Main Content Styles */
.main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 32px 16px;
}

.section-title {
    font-size: 24px;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 24px;
}

.loading-spinner {
    display: flex;
    justify-content: center;
    padding: 48px 0;
}

.spinner {
    width: 48px;
    height: 48px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #00b38a;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

.no-results {
    text-align: center;
    padding: 48px 0;
    color: #666;
}

/* Doctor Card Styles */
.doctor-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    cursor: pointer;
}

.doctor-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.doctor-info {
    display: flex;
    gap: 20px;
}

.doctor-avatar {
    width: 120px;
    height: 120px;
    border-radius: 12px;
    object-fit: cover;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.doctor-details {
    flex: 1;
}

.doctor-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
}

.doctor-name {
    font-size: 1.25rem;
    font-weight: 600;
    color: #2d3748;
    text-decoration: none;
    margin-bottom: 4px;
    display: inline-block;
}

.doctor-name:hover {
    color: #00b38a;
}

.doctor-title {
    color: #4a5568;
    font-size: 0.95rem;
    margin: 4px 0;
}

.hospital-link {
    color: #00b38a;
    text-decoration: none;
}

.hospital-link:hover {
    text-decoration: underline;
}

.department {
    color: #718096;
    font-size: 0.9rem;
}

.price-info {
    text-align: right;
}

.price {
    font-size: 1.5rem;
    font-weight: bold;
    color: #00b38a;
    margin: 0;
}

.consultation-type {
    color: #718096;
    font-size: 0.9rem;
    margin: 4px 0 0;
}

.stats {
    display: flex;
    gap: 20px;
    margin: 12px 0;
    color: #718096;
    font-size: 0.9rem;
}

.rating {
    color: #f6ad55;
}

.introduction {
    color: #4a5568;
    font-size: 0.95rem;
    line-height: 1.5;
    margin: 0;
}

/* Footer Styles */
.footer {
    background-color: #f5f5f5;
    padding: 24px 0;
    margin-top: auto;
}

.bottom-links {
    display: flex;
    justify-content: center;
    gap: 24px;
    flex-wrap: wrap;
}

.bottom-links a {
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.3s ease;
}

.bottom-links a:hover {
    color: #00b38a;
}

/* Animations */
@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* Highlight Style */
:deep(.highlight) {
    background-color: #efc41b;
    padding: 0 2px;
    border-radius: 2px;
}
</style>